
import request from "/utils/omsRequest";
import { moment } from "/utils/core";
import validator from "/utils/validators";
import { bus } from "/utils/core";
import { showToast } from "/utils/common"
const app = getApp();

Component({
  data: {
    show: false, // 产品modal显示
    visibleBuyServiceModal: false, // 购买赠送服务modal显示
    stores: [],
    productIndex: null,
    index: null, // 产品当前操作的索引
    buyServiceIndex: null, // 购买赠送服务当前操作的索引
    selectableList: [], // 可选的购买赠送服务
    selectableProducts: [],
    buyServiceList: [],
    form: {
      buttSheetSysEnclosure: null,
      productId: null,
      shopIdList: [],
      startDate: "",
      endDate: ""
    }
  },
  props: {
    selectedServices: [], // 购买的增值服务
    products: [],
    list: [],
    services: [],
    merchantId: null,
    onChange: () => { }
  },
  didMount() {
    bus.subscribe("productFile", (files) => {
      if (files.length > 0) {
        this.setData({
          "form.buttSheetSysEnclosure": files[0]
        });
      }
    })
  },
  didUpdate() { },
  didUnmount() {
    bus.remove('productFile')
  },
  methods: {
    onRemoveProductForm(e) {
      dd.confirm({
        title: '提示',
        content: '您确定要删除吗？',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        success: (result) => {
          if (result.confirm) {
            this.props.onChange({
              index: e.target.dataset.index,
              buyServiceList: this.data.buyServiceList
            });
          }
        },
      });
    },
    modifyProductForm(e) {
      const productItem = JSON.parse(JSON.stringify(this.props.list[e.target.dataset.index]));
      this.showModal(+productItem.productId);
      this.setData({
        index: e.target.dataset.index,
        productIndex: this.data.selectableProducts.findIndex(item => item.id === +productItem.productId),
        form: productItem
      });
      this.getStoreList(+productItem.productId);
    },
    showDatePicker(e) {
      dd.datePicker({
        format: 'yyyy-MM-dd',
        currentDate: moment().format('YYYY-MM-DD'),
        success: (res) => {
          if (res.date) {
            this.data.form[e.target.dataset.key] = res.date;
            this.setData({
              form: this.data.form
            });
            if (this.data.form.startDate && this.data.form.endDate && this.data.form.startDate >= this.data.form.endDate) {
              this.setData({
                "form.endDate": ""
              });
              dd.alert({
                title: '提示',
                content: '结束时间不能小于等于开始时间',
                buttonText: '确定'
              });
              return;
            }
          }
        },
      });
    },
    catchMethod() { },
    onFormSubmit(e) {
      // 提交  buyServiceList  处理
      Object.assign(this.data.form, e.detail.value);
      let validate = new validator();
      validate.add("checkEmpty", this.data.form.productId, "请选择产品");
      validate.add("checkEmptyArray", this.data.form.shopIdList, "请选择门店");
      validate.add("checkEmpty", this.data.form.startDate, "请选择合同开始时间");
      validate.add("checkEmpty", this.data.form.endDate, "请选择合同结束时间");
      if (this.data.productIndex !== null && this.data.selectableProducts[this.data.productIndex].needQuantityFlag) {
        validate.add("checkIntNotZero", this.data.form.quantity);
      }
      validate.add("checkIntNotZero", this.data.form.amount);
      if (this.data.productIndex !== null && this.data.selectableProducts[this.data.productIndex].buttSheetFlag) {
        validate.add("checkEmpty", this.data.form.buttSheetSysEnclosure, "请上传对接表");
      }
      if (this.data.form.productId === 22) {
        validate.add("checkEmptyArray", this.data.buyServiceList, "购买的增值服务至少添加一条")
      }
      if (validate.check()) {
        this.data.form.quantity = +this.data.form.quantity;
        this.data.form.amount = +this.data.form.amount;
        this.props.onChange({
          index: this.data.index,
          form: this.data.form,
          buyServiceList: this.data.buyServiceList
        });
        this.setData({
          show: false
        });
      }
    },
    showModal(productId) {
      this.setData({
        index: null,
        productIndex: null,
        stores: [],
        show: true,
        buyServiceList: JSON.parse(JSON.stringify(this.props.selectedServices)),
        form: {
          buttSheetSysEnclosure: null,
          productId: null,
          shopIdList: [],
          startDate: "",
          endDate: ""
        }
      });
      const selectedId = this.props.list.map(item => item.productId);
      this.setData({
        selectableProducts: this.props.products.filter(item => productId ? selectedId.includes(item.id) === false || item.id === productId : selectedId.includes(item.id) === false)
      });
    },
    hideModal() {
      this.setData({
        show: false
      })
    },
    onProductChange(e) {
      // productchange  处理buyServiceList
      this.setData({
        buyServiceList: JSON.parse(JSON.stringify(this.props.selectedServices)),
        productIndex: e.detail.value,
        "form.productId": this.data.selectableProducts[e.detail.value].id,
        "form.productName": this.data.selectableProducts[e.detail.value].name,
        "form.shopIdList": []
      });
      this.getStoreList(this.data.form.productId);
    },
    getStoreList(productId) {
      this.setData({
        stores: []
      });
      request({
        url: "/ajax/shop/list",
        data: {
          merchantId: this.props.merchantId,
          productId: productId
        }
      }).then(res => {
        this.setData({
          stores: res.voList
        });
      })
    },
    onUpload() {
      if (app.globalData.systemInfo.platform === "iOS") {
        showToast({ msg: "iOS暂不支持上传附件！请至PC端上传" })
      } else {
        dd.navigateTo({
          url: "/pages/upload/upload?accept=.xls,.xlsx&key=productFile&max=1"
        });
      }
    },
    onRemoveFile() {
      dd.confirm({
        title: '提示',
        content: '您确定要删除吗？',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        success: (result) => {
          if (result.confirm) {
            this.setData({
              "form.buttSheetSysEnclosure": null
            })
          }
        },
      });
    },
    onBuyServiceChange(obj) {
      if (obj.form && this.data.buyServiceIndex !== null) {
        // 处理buyServiceList
        this.data.buyServiceList.splice(this.data.buyServiceIndex, 1, obj.form)
      } else if (obj.form && this.data.buyServiceIndex === null) {
        this.data.buyServiceList.push(obj.form)
      }
      this.setData({
        visibleBuyServiceModal: false,
        buyServiceIndex: null,
        buyServiceList: this.data.buyServiceList
      })
    },
    onServiceHandle(obj) {
      if (obj.index === null && obj.form) {
        this.setData({
          visibleBuyServiceModal: true,
          buyServiceIndex: obj.index
        })
        this.filterServiceSelecteable('BUY')
      } else if (obj.index !== null && obj.form) {
        this.setData({
          visibleBuyServiceModal: true,
          buyServiceIndex: obj.index
        })
        this.filterServiceSelecteable(obj.form.freeServiceType)
        obj.form.serviceIndex = this.data.selectableList.findIndex(item => item.name === obj.form.name);
      } else if (obj.index !== null && obj.form === null) {
        this.onRemoveService(obj.index)
      }
      bus.publish('buyServiceFormInit', obj.form)
    },
    onRemoveService(index) {
      dd.confirm({
        title: '提示',
        content: '您确定要删除吗？',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        success: (result) => {
          if (result.confirm) {
            // 处理buyServiceList
            this.data.buyServiceList.splice(index, 1)
            this.setData({
              buyServiceList: this.data.buyServiceList
            })
          }
        },
      });
    },
    filterServiceSelecteable(freeServiceType) {
      let selectableList = this.props.services.filter(element => {
        return !this.props.selectedServices.find((item, index) => {
          return this.data.index === null ? (item.name === element.name && item.freeServiceType === freeServiceType) : (item.name === element.name && item.freeServiceType === freeServiceType && this.data.index != index)
        })
      })
      this.setData({
        selectableList: selectableList
      });
    }
  },
});
